﻿using NLog;
using ServerMonitor.redisHelper;
using SnmpSharpNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;

namespace ServerMonitor
{
    public class SnmpWorker
    {
        private bool terminate = false;
        private List<SnmpBean> worklist;
        private static ILogger logger = LogManager.GetCurrentClassLogger();
        public RedisHelper redisHelper;

        public SnmpWorker()
        {
            
        }

        public void run()
        {
            if (worklist.Count < 1)
            {
                //worklist为空时，终止标志为true
                terminate = true;
            }
            logger.Info("SnmpWorker start>>>>>>>>>>>");

            try
            {
                while (!terminate)
                {
                    foreach (SnmpBean snmpBean in worklist)
                    {
                        SnmpService.getSwitchStatus(snmpBean);
                        redisHelper.HashSet("switch_status", snmpBean.DeviceName, snmpBean);
                    }
                    Thread.Sleep(10 * 1000); //休眠1分钟
                }
            }
            catch (Exception e)
            {
                logger.Error("exception in snmp worker:{0},{1}",e.Message, e.StackTrace.ToString());
            }
            finally
            {
                if (!terminate)//休眠2秒后重启线程
                {
                    Thread.Sleep(2000);
                    try
                    {
                        Thread.CurrentThread.Abort();
                    }
                    catch (Exception)
                    {

                    }
                    logger.Info("restart snmp worker thread:current thread status:{}", Thread.CurrentThread.ThreadState);
                    new Thread(this.run).Start();
                }
                else
                {
                    logger.Info("snmp worker terminate flag is true,exit thread");
                }
            }
        }

        public void init()
        {
            logger.Info("SnmpWorker init>worklist size:{}", worklist.Count);
            redisHelper = new RedisHelper();
        }

        public List<SnmpBean> Worklist
        {
            get
            {
                return worklist;
            }

            set
            {
                worklist = value;
            }
        }
    }
}
